<template>
  <div class="login">
    <el-form ref="loginRef" :model="loginForm" :rules="loginRules" class="login-form">
      <h3 class="title">{{ title }}</h3>
      <div class="tabChange">
        <div
          class="tabItem"
          :class="{ tabSelectItem: loginForm.type === 'message' }"
          @click="setLoginType('message')"
        >
          快捷登录
        </div>
        <div
          class="tabItem"
          :class="{ tabSelectItem: loginForm.type === 'password' }"
          @click="setLoginType('password')"
        >
          密码登录
        </div>
        <span
          class="tabChangeLine"
          :style="{ left: loginForm.type === 'password' ? '205.5px' : '0px' }"
        ></span>
      </div>

      <!-- 快捷登录 -->
      <template v-if="loginForm.type === 'message'">
        <el-form-item prop="username">
          <el-input
            v-model="loginForm.username"
            class="input"
            maxlength="11"
            clearable
            type="text"
            size="large"
            auto-complete="off"
            placeholder="请输入手机号"
          >
            <template #prefix>
              <div class="prefix phone">
                <img src="~@/assets/images/phone.png" alt="" srcset="" />
              </div>
            </template>
          </el-input>
        </el-form-item>

        <el-form-item prop="code">
          <el-input
            v-model="loginForm.code"
            size="large"
            class="input"
            clearable
            auto-complete="off"
            placeholder="请输入验证码"
            @keyup.enter="handleLogin"
          >
            <template #suffix>
              <span v-if="!isDisabled" class="suffix" @click="sendCode">发送验证码</span>
              <span v-else class="suffixCount">{{ countdown }}秒后重试</span>
            </template>

            <template #prefix>
              <div class="prefix code">
                <img src="~@/assets/images/code.png" alt="" srcset="" />
              </div>
            </template>
          </el-input>
        </el-form-item>
      </template>

      <!-- 账号密码登录 -->
      <template v-if="loginForm.type === 'password'">
        <el-form-item prop="username">
          <el-input
            v-model="loginForm.username"
            class="input"
            type="text"
            size="large"
            clearable
            auto-complete="off"
            placeholder="请输入账号"
            :maxlength="11"
          >
            <template #prefix>
              <div class="prefix account">
                <img src="~@/assets/images/account.png" alt="" srcset="" />
              </div>
            </template>
          </el-input>
        </el-form-item>

        <el-form-item prop="password">
          <el-input
            v-model="loginForm.password"
            class="input"
            type="password"
            clearable
            show-password
            size="large"
            auto-complete="off"
            placeholder="请输入密码"
            @keyup.enter="handleLogin"
          >
            <template #prefix>
              <div class="prefix password">
                <img src="~@/assets/images/password.png" alt="" srcset="" />
              </div>
            </template>
          </el-input>
        </el-form-item>

        <el-form-item prop="code">
          <div class="chapterCode">
            <el-input
              v-model="loginForm.code"
              size="large"
              class="input"
              clearable
              auto-complete="off"
              placeholder="请输入验证码"
              @keyup.enter="handleLogin"
            >
              <template #prefix>
                <div class="prefix code">
                  <img src="~@/assets/images/code.png" alt="" srcset="" />
                </div>
              </template>
            </el-input>
            <div class="suffixcode">
              <img :src="codeUrl" class="login-code-img" @click="getCode" />
            </div>
          </div>
        </el-form-item>
      </template>

      <div class="cacheHandle">
        <el-checkbox v-model="loginForm.rememberMe" class="check">
          <span class="text">自动登录</span>
        </el-checkbox>
        <span class="forget">忘记密码？</span>
      </div>

      <el-form-item>
        <div class="loginClass">
          <el-button
            :loading="loading"
            size="large"
            type="primary"
            class="button"
            @click.prevent="handleLogin"
          >
            <span v-if="!loading" class="text">登&nbsp;&nbsp;&nbsp;&nbsp;录</span>
            <span v-else class="text">登 录 中...</span>
          </el-button>
        </div>
      </el-form-item>
    </el-form>
    <!--  底部  -->
    <div class="el-login-footer">
      <span
        >Copyright © 2024-2025 轻小舟 All Rights Reserved.
        <a target="_blank" href="https://beian.miit.gov.cn/">豫ICP备2025152473</a>
      </span>
    </div>
  </div>
</template>

<script setup>
import Cookies from 'js-cookie';
import { getCodeImg } from '@/api/login';
import { encrypt, decrypt } from '@/utils/jsencrypt';
import useUserStore from '@/store/modules/user';
import { ElMessage } from 'element-plus';
import { onMounted } from 'vue';
import { useRoute, useRouter } from 'vue-router';

const title = import.meta.env.VITE_APP_TITLE;
const userStore = useUserStore();
const route = useRoute();
const router = useRouter();
const codeUrl = ref('');

const loginForm = ref({
  username: '', // admin
  password: '', // admin123
  type: 'password', // 登录方式，默认为快捷登录message password密码
  code: '',
  uuid: '',
  rememberMe: false
});

const loginRules = {
  username: [{ required: true, trigger: 'blur', message: '请输入您的账号' }],
  password: [{ required: true, trigger: 'blur', message: '请输入您的密码' }],
  code: [{ required: true, trigger: 'change', message: '请输入验证码' }]
};

const loading = ref(false);
// 注册开关
const redirect = ref(undefined);

watch(
  route,
  (newRoute) => {
    redirect.value = newRoute.query && newRoute.query.redirect;
  },
  { immediate: true }
);
const loginRef = ref();
const handleLogin = () => {
  loginRef.value.validate((valid) => {
    if (valid) {
      loading.value = true;
      // 勾选了需要记住密码设置在 cookie 中设置记住用户名和密码
      if (loginForm.value.rememberMe) {
        Cookies.set('username', loginForm.value.username, { expires: 30 });
        Cookies.set('password', encrypt(loginForm.value.password), {
          expires: 30
        });
        Cookies.set('rememberMe', loginForm.value.rememberMe, { expires: 30 });
      } else {
        // 否则移除
        Cookies.remove('username');
        Cookies.remove('password');
        Cookies.remove('rememberMe');
      }
      // 调用action的登录方法
      userStore
        .login(loginForm.value)
        .then(() => {
          const query = route.query;
          const otherQueryParams = Object.keys(query).reduce((acc, cur) => {
            if (cur !== 'redirect') {
              acc[cur] = query[cur];
            }
            return acc;
          }, {});
          router.push({ path: redirect.value || '/', query: otherQueryParams });
        })
        .catch(() => {
          loading.value = false;
          // 重新获取验证码
          getCode();
        });
    }
  });
};

const countdown = ref(0);
const isDisabled = ref(false); // 按钮是否禁用

const setLoginType = (type) => {
  loginForm.value.type = type;
};

// 发送短信验证码
const sendCode = () => {
  if (countdown.value > 0) return; // 如果倒计时还在进行中，禁止再次点击
  // 向后端请求验证码（这里模拟请求）
  ElMessage.success('验证码已发送，请注意查收！');
  ElMessage.error('验证码发送失败，无法获取验证码');

  // 启动倒计时
  countdown.value = 60;
  isDisabled.value = true; // 禁用按钮

  const timer = setInterval(() => {
    if (countdown.value > 0) {
      countdown.value--;
    } else {
      clearInterval(timer);
      isDisabled.value = false; // 启用按钮
    }
  }, 1000); // 每秒更新倒计时
};

// 获取图形验证码
function getCode() {
  getCodeImg().then((res) => {
    codeUrl.value = 'data:image/gif;base64,' + res.img;
    loginForm.value.uuid = res.uuid;
  });
}

// forgert
function getCookie() {
  const username = Cookies.get('username');
  const password = Cookies.get('password');
  const rememberMe = Cookies.get('rememberMe');
  // 保留 type、code 字段，避免丢失页面状态
  loginForm.value = {
    ...loginForm.value,
    username: username === undefined ? loginForm.value.username : username,
    password: password === undefined ? loginForm.value.password : decrypt(password),
    rememberMe: rememberMe === undefined ? false : rememberMe === 'true'
  };
}

onMounted(() => {
  getCookie();
  getCode();
});
</script>

<style lang="scss">
@use './index.scss';
</style>
